package org.jash.shop2112.home

import android.content.Context
import android.os.Bundle
import android.view.KeyEvent
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.widget.addTextChangedListener
import androidx.databinding.DataBindingUtil
import com.alibaba.android.arouter.facade.annotation.Route
import com.bumptech.glide.Glide
import com.google.android.material.chip.Chip
import com.google.android.material.search.SearchView
import com.tencent.mmkv.MMKV
import com.youth.banner.BannerConfig
import com.youth.banner.loader.ImageLoader
import dagger.hilt.android.AndroidEntryPoint
import org.jash.shop2112.BR
import org.jash.shop2112.R
import org.jash.shop2112.databinding.FragmentHomeBinding
import org.jash.shop2112.databinding.WordItemBinding
import org.jash.shop2112.entity.Goods
import org.jash.shop2112.mvvm.BaseFragment
import org.jash.shop2112.utils.CommonAdapter
import org.jash.shop2112.utils.Event
import org.jash.shop2112.utils.log


@Route(path = "/shop/home")
@AndroidEntryPoint
class HomeFragment : BaseFragment<FragmentHomeBinding, HomeViewModel>() {
    val adapter by lazy { CommonAdapter<Goods>( { R.layout.goods_item to BR.goods })}
    val searchAdapter by lazy { CommonAdapter<Goods>( { R.layout.goods_item to BR.goods })}
    val kv by lazy { MMKV.defaultMMKV() }
    private val size = 10
    private var page = 1
    override fun initData() {
        viewModel.bannerLiveData.observe(viewLifecycleOwner) {
            binding.banner.update(it.map { it.imagePath }, it.map { it.desc })
        }
        viewModel.goodsLiveData.observe(viewLifecycleOwner) {
            if (page == 1) {
                adapter.clear()
            }
            adapter += it
            binding.refresh.closeHeaderOrFooter()
        }
        viewModel.searchLiveData.observe(viewLifecycleOwner) {
            if (it.isNotEmpty()) {
                binding.keywords.visibility = View.GONE
            }

            searchAdapter.clear()
            searchAdapter += it
        }
        page = 1
        viewModel.loadGoods(page, size)
        viewModel.loadBanner()

    }

    override fun error(throwable: Throwable) {
        super.error(throwable)
        binding.refresh.closeHeaderOrFooter()
    }
    override fun initView() {
        binding.banner.setImageLoader(object :ImageLoader() {
            override fun displayImage(context: Context?, path: Any?, imageView: ImageView?) {
                imageView?.let {
                    Glide.with(it)
                        .load(path)
                        .into(it)
                }
            }
        }).setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE)
        binding.recycler.adapter = adapter
        binding.searchGrid.adapter = searchAdapter
        binding.refresh.setOnRefreshListener {
            page = 1
            viewModel.loadGoods(page, size)
        }
        binding.refresh.setOnLoadMoreListener {
            page++
            viewModel.loadGoods(page, size)
        }
        binding.searchGrid.itemAnimator
//        binding.search.editText.addTextChangedListener {
//            viewModel.search(it.toString())
//        }
        binding.search.editText.setOnEditorActionListener { v, _, event ->
            if (event.action == KeyEvent.ACTION_UP) {
                val keyword = v.text.toString()
                val set = kv.decodeStringSet("keywords", mutableSetOf())
                set?.add(keyword)
                kv.encode("keywords", set)
                viewModel.search(keyword)
            }
            true
        }
        binding.search.addTransitionListener { _, _, state ->
            if (state == SearchView.TransitionState.SHOWING) {
                searchAdapter.clear()
                val set = kv.decodeStringSet("keywords", mutableSetOf())
                binding.keywords.visibility = View.VISIBLE
                binding.keywords.removeAllViews()
                if (set != null) {
                    for (s in set) {
                        val itemBinding = DataBindingUtil.inflate<WordItemBinding>(
                            layoutInflater,
                            R.layout.word_item,
                            binding.keywords,
                            true
                        )
                        itemBinding.word.text = s
                        itemBinding.word.setOnClickListener {
                            binding.search.setText(s)
                            viewModel.search(s)
                        }
                    }
                }
            }
        }
    }

}